package com.aliyun.heiyu.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeConvertUtil {
    private static Logger logger = LoggerFactory.getLogger(TimeConvertUtil.class);
    public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String HOURMINUTE_PATTERN = "HH:mm";

    public static Timestamp string2Stamp(String str, SimpleDateFormat sdf) {
        if(str == null || str.isEmpty()){
            return null;
        }
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            logger.error(e.getMessage());
        }
        if(date == null){
            return null;
        }
        return new Timestamp(date.getTime());
    }
    public static String getStringDate(Date date) {
        String dateString="";
        if(null==date){
            return dateString;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateString = formatter.format(date);
        return dateString;
    }
    public static String stamp2String(Timestamp stamp, SimpleDateFormat sdf) {
        if(stamp == null){
            return "";
        }
        return sdf.format(stamp);
    }

    public static String mysqlTimeSubstring(String time) {
        if(time == null){
            return "";
        }
        return time.substring(0, time.indexOf("."));
    }

    public static String millisecondToDate(Long millisecond){
        Date date = new Date(millisecond);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    public static long dateToMillisecond(String dateTime) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  calendar.getTimeInMillis();
    }

    public static String customizedTime(int field, int count, String pattern) {
        //定制相对时间
        /*field
        Calendar.DAY_OF_MONTH
        Calendar.HOUR_OF_DAY
        Calendar.**
         */
        /*pattern
        yyyy-MM-dd
        yyyy-MM-dd hh:mm:ss
        */
        Date dNow = new Date();  //当前时间
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);
        calendar.add(field, count); //设置为前3天
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String time = format.format(calendar.getTime());
        return time;
    }

}
